<?php 
function monthfirstday($num){
  date_default_timezone_set("PRC");
  $currentTime = time();
  $cyear = floor(date("Y",$currentTime));
  $cMonth = floor(date("m",$currentTime));
  for($i=0;$i<$num;$i++){
  $nMonth = $cMonth-$i;
  $cyear = $nMonth == 0 ? ($cyear-1) : $cyear;
  $nMonth = $nMonth <= 0 ? 12+$nMonth : '0'.$nMonth;
  $date = $cyear."-".$nMonth."-1";
  $firstday = date('01 00:00:00.000', strtotime($date));
  $lastday = date('t 23:59:59.999', strtotime($date));

  // echo $cyear."年".$nMonth."月";
  // echo "第一天:".$firstday;
  // echo "最后一天:".$lastday,"";
}
  return  $cyear.'-'.$nMonth.'-'.$firstday;



}
function monthlastday($num){
  date_default_timezone_set("PRC");
  $currentTime = time();
  $cyear = floor(date("Y",$currentTime));
  $cMonth = floor(date("m",$currentTime));
  for($i=0;$i<$num;$i++){
  $nMonth = $cMonth-$i;
  $cyear = $nMonth == 0 ? ($cyear-1) : $cyear;
  $nMonth = $nMonth <= 0 ? 12+$nMonth : '0'.$nMonth;
  $date = $cyear."-".$nMonth."-1";
  $firstday = date('01 00:00:00.000', strtotime($date));
  $lastday = date('t 00:00:000', strtotime($date));

  // echo $cyear."年".$nMonth."月";
  // echo "第一天:".$firstday;
  // echo "最后一天:".$lastday,"";
}
  return  $cyear.'-'.$nMonth.'-'.$lastday;


}

function month($num){
  date_default_timezone_set("PRC");
  $currentTime = time();
  
  $cMonth = floor(date("m",$currentTime));
  for($i=0;$i<$num;$i++){
  $nMonth = $cMonth-$i;
  
  $nMonth = $nMonth <= 0 ? 12+$nMonth : $nMonth;
  

  // echo $cyear."年".$nMonth."月";
  // echo "第一天:".$firstday;
  // echo "最后一天:".$lastday,"";
}
  return  $nMonth;
  


}

/**
   * 使用phpmailer发送邮件
   * @param string $to 收件人
   * @param string $subject 主题
   * @param string $body 正文
   * @param string $attachment_dir 附件地址
   * @return boolean
   */
  function send_mail($to,$subject,$body='',$company,$attachment_dir=''){
    require_once COMMON_PATH.'Plugin/PHPMailer/class.phpmailer.php';
    $mail = new PHPMailer;
    $mail->CharSet ="utf-8";//设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP(); // 设定使用SMTP服务
    $mail->SMTPDebug  = 1;// 启用SMTP调试功能1 = errors and messages 2 = messages only
    $mail->SMTPAuth   = true;                  // 启用 SMTP 验证功能
    $mail->SMTPSecure = "smtp";                 // 安全协议
   
    $mail->Host       = 'smtp.163.com';//'smtp.163.com'      // SMTP 服务器
    $mail->Port       = '25';//'25'                   // SMTP服务器的端口号
    $mail->Username   = 'hnjssoftsend';//'lwchun1983' hnjssoftsend // SMTP服务器用户名
    $mail->Password   = '123456789'; //'DODIdodi123'           // SMTP服务器密码
    $mail->SetFrom('hnjssoftsend@163.com',$company);//'lwchun1983@163.com'
    $mail->AddReplyTo('hnjssoftsend@163.com',$company);//增加回复标签，参数1地址，参数2名称

    //组装新的格式    标题 收件人 内容  附件
    $mail->Subject = $subject;  //主题
    $mail->MsgHTML($body); //正文  支持html格式
    $mail->AddAddress($to, " ");//增加收件人 参数1为收件人邮箱，参数2为收件人称呼
    if(!empty($attachment_dir)){
      $mail->AddAttachment($attachment_dir);//附件的路径和附件名
    }

    return $mail->Send();
  }

function send(){
   require_once COMMON_PATH.'Plugin/PHPMailer/class.phpmailer.php';
  $mail = new PHPMailer();
    echo "$mail = new PHPMailer();";
     $mail->CharSet ="utf-8";
    $mail->IsSMTP();                                      // set mailer to use SMTP
    $mail->Host = "smtp.sina.com";  // specify main and backup server
    $mail->SMTPAuth = true;     // turn on SMTP authentication
    $mail->Username = "a1062129814@sina.com";  // SMTP username
    $mail->Password = "a8681747"; // SMTP password
     
    $mail->From = "a1062129814@sina.com";
    $mail->FromName = "Mailer";
    $mail->AddAddress("a1062129814@sina.com");                  // name is optional
    $mail->AddReplyTo("a1062129814@sina.com", "Information");
     
    $mail->WordWrap = 50;                                 // set word wrap to 50 characters
    $mail->IsHTML(true);                                  // set email format to HTML
     
    $mail->Subject = "测试邮件";
    $mail->Body    = "测试的邮件";
    $mail->AltBody = "This is the body in plain text for non-HTML mail clients";
     
    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }
     
    echo "Message has been sent";
}
 
//创建数据库连接   



// $servername = "cssksoft.com";
// $username = "jstzgssyb";
// $password = "jstzgssyb";
// $dbname = "jstzgs";
   
// $conn=jscon($servername,$username,$password,$dbname);


// $lr=jsOpenSql($conn,"SELECT * FROM dKSqInfo ");
// print_r($lr);
//echo jsExecSql($conn,"insert into login (uname,upass)values(?,?)",array('aimy','111111'));


function returnApiSuccess($msg = null,$data = array()){
  $result = array(
    'flag' => 'Success',
    'msg' => $msg,
    'data' =>$data
  );
  print json_encode($result);
}
  
/**
 * @param null $msg  返回具体错误的提示信息
 * @param flag success CURD 操作失败
 * Function descript:返回标志信息 ‘Error'，和提示信息的json 数组
 */
function returnApiError($msg = null){
  $result = array(
    'flag' => 'Error',
    'msg' => $msg,
  );
  print json_encode($result);
}
  
/**
 * @param null $msg  返回具体错误的提示信息
 * @param flag success CURD 操作失败
 * Function descript:返回标志信息 ‘Error'，和提示信息，当前系统繁忙，请稍后重试；
 */
function returnApiErrorExample(){
  $result = array(
    'flag' => 'Error',
    'msg' => '当前系统繁忙，请稍后重试！',
  );
  print json_encode($result);
}
  
/**
 * @param null $data
 * @return array|mixed|null
 * Function descript: 过滤post提交的参数；
 *
 */
  
 function checkDataPost($data = null){
  if(!empty($data)){
    $data = explode(',',$data);
    foreach($data as $k=>$v){
      if((!isset($_POST[$k]))||(empty($_POST[$k]))){
        if($_POST[$k]!==0 && $_POST[$k]!=='0'){
          returnApiError($k.'值为空！');
        }
      }
    }
    unset($data);
    $data = I('post.');
    unset($data['_URL_'],$data['token']);
    return $data;
  }
}
  
/**
 * @param null $data
 * @return array|mixed|null
 * Function descript: 过滤get提交的参数；
 *
 */
function checkDataGet($data = null){
  if(!empty($data)){
    $data = explode(',',$data);
    foreach($data as $k=>$v){
      if((!isset($_GET[$k]))||(empty($_GET[$k]))){
        if($_GET[$k]!==0 && $_GET[$k]!=='0'){
          returnApiError($k.'值为空！');
        }
      }
    }
    unset($data);
    $data = I('get.');
    unset($data['_URL_'],$data['token']);
    return $data;
  }
}

//创建数据库连接   
function jscon($servername,$username,$password,$dbname)
{
 try{  
     
    //    $conn = new PDO("sqlsrv:server=$servername;Database=$dbname",$username,$password);  
      //  $conn = new PDO( "sqlsrv:server=$serverName;Database = $database", $uid, $pwd); 
        $conn = new PDO("sqlsrv:server=$servername;Database=$dbname",$username,$password);  
        $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); 
        return $conn;
          
   }
   catch(PDOException $e)
   {
      return  $e->getMessage();
       echo "连接失败"; 
   }  
    
}
   
   
//查询代码，输入查询语句和参数数组，返回数组结果  
function jsOpenSql($conn,$strSql,$arrayName=Null)
{
     $stmt = $conn->prepare($strSql);
     
     if (count($arrayName)>0){
        $stmt->execute($arrayName);
    }
     else{
        $stmt->execute();
    }


      while($row = $stmt->fetch(PDO::FETCH_ASSOC))
      {
         $lr[]=$row; 
      }  
      //echo  $stmt->rowCount().'条<br>';  
      return $lr;
      
}

//执行代码，输入查询语句和参数数组，返回数组结果  
function jsExecSql($conn,$strSql,$arrayName=Null)
{
     $stmt = $conn->prepare($strSql);
     
   try {
      
     if (count($arrayName)>0)
     {$stmt->execute($arrayName);}
     else
      {$stmt->execute();}

       return '1'; //执行成功返回1
   }
   catch(PDOException $e)
   {
      return $e->getMessage();  //执行失败返回错误代码
   }        
}
   
//关闭数据库连接，一般不需要使用
function jsCloseCon()
{
      $conn = null;  
}


// $servername = "cssksoft.com";
// $username = "jstzgssyb";
// $password = "jstzgssyb";
// $dbname = "jstzgs";
   
// $conn=jscon($servername,$username,$password,$dbname);


// $lr=jsOpenSql($conn,"SELECT * FROM dKSqInfo ");
// print_r($lr);
//echo jsExecSql($conn,"insert into login (uname,upass)values(?,?)",array('aimy','111111'));

function tp_return($code = 0, $msg='ok')
{
  return array(
    'code'=>$code,
    'msg'=>$msg
  );
}
/**
 * [阿里大鱼短信发送]
 */
function send_sms_aldy( $phone , $code='' ){
  if(preg_match("/^1[34578]\d{9}$/", $mobile)){
    return tp_return(1101 , '手机号码不合法');
  }
  $api_url = C('cfg_ALIDAYU_APIURL');
  $accessKeyId = C('cfg_ALIDAYU_ACCESSKEYID');
  $accessSecret = C('cfg_ALIDAYU_SECRET');
  $cutime = time();
  date_default_timezone_set('GMT');
  $df = date("Y-m-d",$cutime).'T'.date("H:i:s",$cutime).'Z';
  $param['SignatureMethod'] = "HMAC-SHA1";
  $param['SignatureNonce'] = createUUid();
  $param['AccessKeyId'] = $accessKeyId;
  $param['SignatureVersion'] = "1.0";
  $param['Timestamp'] = $df;
  $param['Format'] = "JSON";
  
  $param['Action'] = "SendSms";
  $param['Version'] = C('cfg_ALIDAYU_VERSION');
  $param['RegionId'] = "cn-hangzhou";
  $param['PhoneNumbers'] = $phone;
  $param['SignName'] = C('cfg_ALIDAYU_SIGN_NAME');
  if($code){
    //验证码模板
    $param['TemplateCode'] = C('cfg_ALIDAYU_TemplateCode');//C('alidayu.register_tpl.code');
    $param['TemplateParam'] = "{\"code\":\"$code\"}";//C('alidayu.register_tpl.param');
  }else{
    //短信推送模板
    $param['TemplateCode'] = C('cfg_ALIDAYU_TemplateCode');
  }

  ksort($param);
  $url = http_build_query($param);
  $ture_url = $url;
  $prefix = "GET&".urlencode("/")."&";
  $finalfix = speacialChar($url);
  $new_url = $prefix.$finalfix;
  $signature = urlencode($hmac_sha1_str);  
  $signature = base64_encode(hash_hmac('sha1', $new_url, $accessSecret.'&', true));
  $signature = speacialChar($signature);
  $url = $api_url.'?Signature='.$signature.'&'.$ture_url;
  $ret = curl_get($url);
  if($ret['Code']=='OK'){
    return tp_return( 0 , '发送成功' );
  }else{
    return tp_return( 1 , $ret['Message'] );
  }
}

/**
 * [createUUid description]
 * @return [type] [description]
 */
function createUUid()
{
  if (function_exists ( 'com_create_guid' )) {
    return com_create_guid ();
  } else {
    mt_srand ( ( double ) microtime () * 10000 ); 
    $charid = strtoupper ( md5 ( uniqid ( rand (), true ) ) ); //根据当前时间（微秒计）生成唯一id.
    $hyphen = chr ( 45 ); // "-"
    $uuid = '' . //chr(123)// "{"
    substr ( $charid, 0, 8 ) . $hyphen . substr ( $charid, 8, 4 ) . $hyphen . substr ( $charid, 12, 4 ) . $hyphen . substr ( $charid, 16, 4 ) . $hyphen . substr ( $charid, 20, 12 );
    //.chr(125);// "}"
    return $uuid;
  }
}

function speacialChar($str)
{
  $str = urlencode($str);
  return $str;
}

/**
 * [curl_get description]
 * @param  [type] $url [description]
 * @return [type]      [description]
 */
function curl_get($url){
  $curl = curl_init();
  curl_setopt ( $curl, CURLOPT_URL, $url );
    curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
  curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE );
  curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
  $output = curl_exec ( $curl );
  if(curl_errno($curl)){
      echo 'Curl error: ' . curl_error($curl);
        exit;
    }
  curl_close ( $curl );
  $ret = json_decode($output,true);
  return $ret;
}




 ?>